<template>
  <div class="tag-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">标签管理</h1>
      <p class="page-description">管理图书标签，为图书添加分类标识</p>
    </div>

    <!-- 搜索和操作栏 -->
    <div class="search-bar">
      <div class="search-form">
        <el-input
          v-model="searchForm.name"
          placeholder="请输入标签名称"
          style="width: 200px; margin-right: 10px;"
          clearable
          @keyup.enter="loadTagList"
        />
        <el-button type="primary" @click="loadTagList">
          <i class="fas fa-search"></i> 搜索
        </el-button>
        <el-button @click="resetSearch">
          <i class="fas fa-refresh"></i> 重置
        </el-button>
      </div>
      <div class="action-buttons">
        <el-button type="primary" @click="showAddDialog">
          <i class="fas fa-plus"></i> 添加标签
        </el-button>
      </div>
    </div>

    <!-- 标签列表 -->
    <div class="table-container">
      <el-table
        :data="tagList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="标签名称" min-width="150" align="center"/>
        <el-table-column label="标签颜色" width="120">
          <template #default="{ row }">
            <span 
              :class="row.tagColor" 
              class="inline-block px-2 py-1 rounded text-white text-xs"
            >
              {{ row.name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="showEditDialog(row)"
            >
              <i class="fas fa-edit"></i> 编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteTag(row)"
            >
              <i class="fas fa-trash"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadTagList"
          @current-change="loadTagList"
        />
      </div>
    </div>

    <!-- 添加/编辑标签对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <!-- 表单内容 -->
      <el-form
        ref="formRef"
        :model="tagForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="tagForm.name" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="标签颜色" prop="tagColor">
          <div class="color-selector">
            <div class="color-options">
              <div
                v-for="color in colorOptions"
                :key="color.value"
                :class="[
                  'color-option',
                  color.value,
                  { 'selected': tagForm.tagColor === color.value }
                ]"
                @click="selectColor(color.value)"
              >
                {{ color.label }}
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <!-- 对话框底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { merchantAPI } from '@/api/merchant'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()

const searchForm = reactive({
  name: ''
})

const tagForm = reactive({
  id: null,
  name: '',
  tagColor: 'bg-blue-500'
})

const tagList = ref([])

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 颜色选项
const colorOptions = [
  { label: '蓝色', value: 'bg-blue-500' },
  { label: '绿色', value: 'bg-green-500' },
  { label: '红色', value: 'bg-red-500' },
  { label: '黄色', value: 'bg-yellow-500' },
  { label: '紫色', value: 'bg-purple-500' },
  { label: '粉色', value: 'bg-pink-500' },
  { label: '青色', value: 'bg-cyan-500' },
  { label: '橙色', value: 'bg-orange-500' },
  { label: '灰色', value: 'bg-gray-500' },
  { label: '靛蓝', value: 'bg-indigo-500' },
  { label: '玫瑰', value: 'bg-rose-500' },
  { label: '蓝绿', value: 'bg-teal-500' }
]

const dialogTitle = computed(() => isEdit.value ? '编辑标签' : '添加标签')

const formRules = {
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 1, max: 20, message: '标签名称长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  tagColor: [
    { required: true, message: '请选择标签颜色', trigger: 'change' }
  ]
}

// 方法
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const loadTagList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }

    const response = await merchantAPI.getTagList(params)
    tagList.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('加载标签列表失败:', error)
    ElMessage.error('加载标签列表失败')
  } finally {
    loading.value = false
  }
}

const resetSearch = () => {
  searchForm.name = ''
  pagination.current = 1
  loadTagList()
}

const showAddDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

const showEditDialog = (tag) => {
  isEdit.value = true
  dialogVisible.value = true
  Object.assign(tagForm, tag)
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(tagForm, {
    id: null,
    name: '',
    tagColor: 'bg-blue-500'
  })
}

const selectColor = (color) => {
  tagForm.tagColor = color
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (isEdit.value) {
      await merchantAPI.updateTag(tagForm.id, tagForm)
      ElMessage.success('更新标签成功')
    } else {
      await merchantAPI.createTag(tagForm)
      ElMessage.success('创建标签成功')
    }
    
    dialogVisible.value = false
    loadTagList()
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error(error.response?.data?.message || '操作失败')
  }
}

const deleteTag = async (tag) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除标签"${tag.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await merchantAPI.deleteTag(tag.id)
    ElMessage.success('删除标签成功')
    loadTagList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除标签失败:', error)
      ElMessage.error(error.response?.data?.message || '删除标签失败')
    }
  }
}

// 生命周期
onMounted(() => {
  loadTagList()
})
</script>

<style scoped>
.tag-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0 0 8px 0;
}

.page-description {
  color: #666;
  margin: 0;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.search-form {
  display: flex;
  align-items: center;
}

.table-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.color-selector {
  width: 100%;
}

.color-options {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

.color-option {
  padding: 8px 12px;
  border-radius: 4px;
  color: white;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid transparent;
}

.color-option:hover {
  transform: scale(1.05);
}

.color-option.selected {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
</style>
